package com.tale.competition.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {

    private static final String SECRET = "tale_token"; // 加密标识(秘钥）

    /**
     * 生成jwt
     * @param id
     * @param userName
     * @param uType
     * @return
     */
    public static String createToken(String id, String userName, String uType){

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR, 24 * 6); // 过期时间

        Date expireTime = calendar.getTime();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("alg", "HS256");  // 加密算法
        map.put("typ", "JWT");


        Map<String, Object> info = new HashMap<String, Object>();
        info.put("id", id);
        info.put("userName", userName);
        info.put("uType", uType);

        String token = Jwts.builder().setHeader(map)
                .setClaims(info)
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .setExpiration(expireTime)
                .compact();

        return token;

    }

    /**
     * 解析jwt
     * @param token
     * @return
     */
    public static Claims decryptJWT(String token){

        return Jwts.parser().setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    }
}
